package cn.lb.framework.poi.excel.imports.verifys;

import cn.lb.framework.poi.excel.entity.ImportParams;
import cn.lb.framework.poi.excel.entity.params.ExcelImportEntity;
import cn.lb.framework.poi.excel.entity.params.ExcelVerifyEntity;
import cn.lb.framework.poi.excel.entity.result.ExcelVerifyHanlderResult;
import cn.lb.framework.poi.exception.excel.ExcelImportException;
import cn.lb.framework.poi.exception.excel.enums.ExcelImportEnum;
import cn.lb.framework.poi.handler.inter.IExcelVerifyHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 校验服务
 */
public class VerifyHandlerServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(VerifyHandlerServer.class);

    private final static ExcelVerifyHanlderResult DEFAULT_RESULT = new ExcelVerifyHanlderResult(true);

    private void addVerifyResult(ExcelVerifyHanlderResult hanlderResult, ExcelVerifyHanlderResult result) {
        if (!hanlderResult.isSuccess()) {
            result.setSuccess(false);
            result.setMsg((StringUtils.isEmpty(result.getMsg()) ? "" : result.getMsg() + " , ") + hanlderResult.getMsg());
        }
    }

    /**
     * 校验数据
     *
     * @param object
     * @param value
     * @param name
     * @param verify
     * @param excelVerifyHandler
     * @return
     */
    public ExcelVerifyHanlderResult verifyData(Object object, Object value, String name, ExcelVerifyEntity verify, IExcelVerifyHandler excelVerifyHandler) {
        if (verify == null) {
            return DEFAULT_RESULT;
        }
        ExcelVerifyHanlderResult result = new ExcelVerifyHanlderResult(true, "");
        if (verify.isNotNull()) {
            addVerifyResult(BaseVerifyHandler.notNull(name, value), result);
        }
        if (verify.isEmail()) {
            addVerifyResult(BaseVerifyHandler.isEmail(name, value), result);
        }
        if (verify.isMobile()) {
            addVerifyResult(BaseVerifyHandler.isMobile(name, value), result);
        }
        if (verify.isTel()) {
            addVerifyResult(BaseVerifyHandler.isTel(name, value), result);
        }
        if (verify.getMaxLength() != -1) {
            addVerifyResult(BaseVerifyHandler.maxLength(name, value, verify.getMaxLength()), result);
        }
        if (verify.getMinLength() != -1) {
            addVerifyResult(BaseVerifyHandler.minLength(name, value, verify.getMinLength()), result);
        }
        if (StringUtils.isNotEmpty(verify.getRegex())) {
            addVerifyResult(BaseVerifyHandler.regex(name, value, verify.getRegex(), verify.getRegexTip()), result);
        }
        if (verify.isInterHandler()) {
            if (excelVerifyHandler != null) {
                addVerifyResult(excelVerifyHandler.verifyHandler(object, name, value), result);
            }
        }
        return result;
    }

    /**
     * 验证数据
     * @param object
     * @param value
     * @param name
     * @param excelParams
     * @param params
     * @return
     */
    public ExcelVerifyHanlderResult verifyData(Object object, String value, String name, Map<String,
            ExcelImportEntity> excelParams, ImportParams params) {
        ExcelVerifyHanlderResult result = null;
        try {
            Object val = verifyValue(object,excelParams,name,value);
            result = verifyData(object, val, name, excelParams.get(name).getVerify(), params.getVerifyHanlder());
            result.setObj(val);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            result = new ExcelVerifyHanlderResult(false, name + "数据不规范");
        }
        return result;
    }


    public Object verifyValue(Object object, Map<String, ExcelImportEntity> excelParams, String titleString, String value) {
        ExcelImportEntity entity = excelParams.get(titleString);
        String xclass = "class java.lang.Object";
        if (!(object instanceof Map)) {
            Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? entity
                    .getMethods().get(entity.getMethods().size() - 1) : entity.getMethod();
            Type[] ts = setMethod.getGenericParameterTypes();
            xclass = ts[0].toString();
        }
        if (entity != null) {
            value = replaceValue(entity.getReplace(), value);
        }
        return getValueByType(xclass, value, entity);
    }

    /**
     * 校验值是否合法
     *
     * @param xclass
     * @param result
     * @param entity
     * @return
     */
    private Object getValueByType(String xclass, String result, ExcelImportEntity entity) {
        try {
            if (result == null || "".equals(String.valueOf(result))) {
                return null;
            }

            if ("class java.util.Date".equals(xclass)) {
                return DateUtil.getJavaDate(Double.valueOf(result));
            } else if ("class java.lang.Boolean".equals(xclass) || "boolean".equals(xclass)) {
                return Boolean.valueOf(String.valueOf(result));
            } else if ("class java.lang.Double".equals(xclass) || "double".equals(xclass)) {
                String rt = String.valueOf(result);
                if (rt.endsWith(".0")) {
                    rt = rt.substring(0, rt.indexOf("."));
                }
                Double temp=0d;
                try{
                    temp=Double.valueOf(rt);
                }catch (Exception e){
                    return null;
                }
                return temp;
            } else if ("class java.lang.Long".equals(xclass) || "long".equals(xclass)) {
                return Long.valueOf(String.valueOf(result));
            } else if ("class java.lang.Float".equals(xclass) || "float".equals(xclass)) {
                return Float.valueOf(String.valueOf(result));
            } else if ("class java.lang.Integer".equals(xclass) || "int".equals(xclass)) {
                return Integer.valueOf(String.valueOf(result));
            } else if ("class java.math.BigDecimal".equals(xclass)) {
                return new BigDecimal(String.valueOf(result));
            } else if ("class java.lang.String".equals(xclass)) {
                return String.valueOf(result);
            }
            return result;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR);
        }
    }

    /**
     * 替换值
     *
     * @param replace
     * @param result
     * @return
     */
    private String replaceValue(String[] replace, String result) {
        if (replace != null && replace.length > 0) {
            String[] tempArr;
            for (int i = 0; i < replace.length; i++) {
                tempArr = replace[i].split("_");
                if (result.equals(tempArr[0])) {
                    return tempArr[1];
                }
            }
        }
        return result;
    }
}
